package com.lzh.async.thread;

import com.alibaba.ttl.TtlCallable;
import com.alibaba.ttl.TtlRunnable;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * @author zhehen.lu
 * @date 2025/8/13 19:50
 */
public class RequestContextAwarePoolExecutor extends ThreadPoolTaskExecutor {
    public RequestContextAwarePoolExecutor() {
    }

    @Override
    public void execute(Runnable runnable) {
        RequestContextAwareRunnable contextAwareRunnable = new RequestContextAwareRunnable(runnable, RequestContextHolder.currentRequestAttributes());
        Runnable ttlRunnable = TtlRunnable.get(contextAwareRunnable);
        super.execute(ttlRunnable);
    }

    @Override
    public <T> Future<T> submit(Callable<T> task) {
        RequestContextAwareCallable<T> contextAwareCallable = new RequestContextAwareCallable(task, RequestContextHolder.currentRequestAttributes());
        Callable ttlCallable = TtlCallable.get(contextAwareCallable);
        return super.submit(ttlCallable);
    }

    @Override
    public Future<?> submit(Runnable task) {
        RequestContextAwareRunnable contextAwareRunnable = new RequestContextAwareRunnable(task, RequestContextHolder.currentRequestAttributes());
        Runnable ttlRunnable = TtlRunnable.get(contextAwareRunnable);
        return super.submit(ttlRunnable);
    }

    @Override
    public ListenableFuture<?> submitListenable(Runnable task) {
        RequestContextAwareRunnable contextAwareRunnable = new RequestContextAwareRunnable(task, RequestContextHolder.currentRequestAttributes());
        Runnable ttlRunnable = TtlRunnable.get(contextAwareRunnable);
        return super.submitListenable(ttlRunnable);
    }

    @Override
    public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
        RequestContextAwareCallable<T> contextAwareCallable = new RequestContextAwareCallable(task, RequestContextHolder.currentRequestAttributes());
        Callable ttlCallable = TtlCallable.get(contextAwareCallable);
        return super.submitListenable(ttlCallable);
    }
}
